package vn.com.vega.chacha.v2;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;

import vn.com.vega.chacha.R;
import vn.com.vega.music.clientserver.JsonAuth;
import vn.com.vega.music.clientserver.JsonSong;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.device.FileStorage;
import vn.com.vega.music.player.ChaChaProgressDialog;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.custom.BottomPlayerView;
import vn.com.vega.music.view.custom.BottomPlayerView.ShowHideBottomPlayerListener;
import vn.com.vega.music.view.custom.ChaChaDialog;
import vn.com.vega.music.view.custom.ChaChaDialog.OnCloseDialogListener;
import vn.com.vega.music.view.custom.TextBox;
import vn.com.vega.music.view.custom.TopTaskbarView;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

public class SettingAccount extends ActivityBase implements
		SeekBar.OnSeekBarChangeListener, Const, OnClickListener {

	protected static final int GET_ACC_INFO_SUCCESS = 1;
	protected static final int GET_ACC_INFO_FAILED = 2;
	protected static final int UPLOAD_AVATAR_SUCCESS = 13;
	protected static final int UPLOAD_AVATAR_FAILED = 14;

	protected static final int UNSUBCRIBE_FAILED = 4;
	protected static final int UNSUBCRIBE_SUCCESS = 5;

	protected static final int LOGOUT_SUCCESS = 11;
	protected static final int LOGOUT_FAIL = 15;
	protected static final int CHANGE_PASS_SUCCESS = 16;
	protected static final int CHANGE_PASS_FAIL = 17;


	public static final int VALUE_CAMERA = 0;
	public static final int VALUE_GALLERY = 1;

	private JsonAuth identify;
	private JsonAuth unsubscribe;

	private TextView txtFullName;
	private TextView txtPhoneNumber;
	private ImageView imgAvatar;

	private SeekBar totalMemorySeekBar;
	private TextView memoryCurrentuse;
	private TextView memoryPercentUse;
	private TextView memoryAllow;
	private TextView memoryMax;

	private View showAccountInfo, unsubcribe, changepass, logout;
	private DataStore dataStore;

	private Appinstant mApp;
	private BottomPlayerView mBottomPlayerView;
	private View mViewReplacePlayer;
	private TopTaskbarView mTopTaskbarView;
	private ChaChaDialog logoutDialog;
	private ChaChaDialog unsubscriDialog;

	private ChaChaProgressDialog mProgressDialog;

	static class SettingHandler extends Handler {
		WeakReference<SettingAccount> settingAct;

		public SettingHandler(SettingAccount act) {
			settingAct = new WeakReference<SettingAccount>(act);
		}

		private boolean checkIsLive() {
			SettingAccount settingAccount = settingAct.get();
			if (settingAccount == null || settingAccount.isDestroy) {
				return false;
			}
			return true;
		}

		@Override
		public void handleMessage(Message msg) {
			if (!checkIsLive()) {
				removeCallbacksAndMessages(null);
				return;
			}
			SettingAccount setting = settingAct.get();
			setting.hideProgress();

			switch (msg.what) {
			case CHANGE_PASS_SUCCESS:
				setting.showToast("Đổi mật khẩu thành công");
				break;
			case CHANGE_PASS_FAIL:
				setting.showToast("Đổi mật khẩu thất bại");
				break;
			
			case GET_ACC_INFO_FAILED:
				if (!Util.checkStringIsemptyOrNull(setting.identify.getErrorMessage().trim())) {
					Util.showAlert(setting, setting.identify.getErrorMessage());
				}
				break;
			case GET_ACC_INFO_SUCCESS:
				if (!Util.checkStringIsemptyOrNull(setting.identify.accountInfo.trim())) {
					Util.showAlert(setting, setting.identify.accountInfo);
				}
				break;
			case UNSUBCRIBE_FAILED:
				if (!setting.unsubscribe.getErrorMessage().trim().equals("")) {
					Util.showAlert(setting,
							setting.unsubscribe.getErrorMessage());
				}
				break;
			case UNSUBCRIBE_SUCCESS:
				// showAlert(getString(R.string.setting_unsubcribe_success));
//				setting.restartApp(setting
//						.getString(R.string.setting_unsubcribe_success));
//				break;
			case LOGOUT_SUCCESS:
				setting.actionDoWhenLogoutSuccess();
//				JsonBase.clearServerSessionInvalidListener();
//				DownloadUtil.stopDownload();
//				// // Stop sync thread
////				SyncUtil.stopSync(setting.getApplicationContext());
//				// // Stop MusicPlayer
//				Util.stop();
//
//				// request login again
//				Bundle b = new Bundle();
//				b.putBoolean(LoginActivity.NEED_AUTHENTICATION, true);
//				b.putString(Const.KEY_MSISDN, setting.dataStore.getMsisdn());
//				b.putString(Const.KEY_PASSWORD,
//						setting.dataStore.getSavedPassword());
//
//				// setting.dataStore.setConfig(KEY_IS_LOGOUT, "true");
//
//				b.putBoolean(LoginActivity.NEED_AUTHENTICATION, true);
//				Intent login = new Intent(setting, LoginActivity.class);
//				login.putExtras(b);
//				login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
//						| Intent.FLAG_ACTIVITY_SINGLE_TOP);
//				setting.startActivity(login);
//				setting.sendStickyBroadcastLogout();
//				setting.finish();
				break;
			case LOGOUT_FAIL:
				setting.showToast("Đăng xuất thất bại");
				break;
			case UPLOAD_AVATAR_FAILED:
				// Toast.makeText(mContext, "Upload không thành công",
				// Toast.LENGTH_SHORT).show();
				break;
			case UPLOAD_AVATAR_SUCCESS:
				// Toast.makeText(mContext, "Upload thành công",
				// Toast.LENGTH_SHORT).show();
				break;
			}
		}
	}

	private SettingHandler mHandler = new SettingHandler(SettingAccount.this);

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mApp = (Appinstant) getApplication();
		setContentView(R.layout.layout_activity_setting);

		mBottomPlayerView = (BottomPlayerView) findViewById(R.id.bottomPlayerView_setting_account);
		mViewReplacePlayer = findViewById(R.id.view_replace_bottom_player);
		mBottomPlayerView.setShowHideListener(showHideBottomPlayerListener);

		mTopTaskbarView = (TopTaskbarView) findViewById(R.id.topTaskbarView_account_setting);
		mTopTaskbarView.showBackButton();
		mTopTaskbarView.changeToTitleOnly(getString(R.string.account_setting));
		dataStore = DataStore.getInstance();

		txtFullName = (TextView) findViewById(R.id.account_info_full_name);
		txtPhoneNumber = (TextView) findViewById(R.id.account_info_phone_number);
		imgAvatar = (ImageView) findViewById(R.id.account_info_avatar);

		imgAvatar.setOnClickListener(onUploadAvatarBtnListener);

		// set Listener
		totalMemorySeekBar = (SeekBar) findViewById(R.id.seekBar);
		totalMemorySeekBar.setOnSeekBarChangeListener(this);

		memoryCurrentuse = (TextView) findViewById(R.id.setting_screen_used_memory_txt);
		memoryPercentUse = (TextView) findViewById(R.id.tv_memory_percent_used);
		memoryAllow = (TextView) findViewById(R.id.setting_screen_total_memory_txt);
		memoryMax = (TextView) findViewById(R.id.setting_screen_total_memory_max_txt);

		showAccountInfo = findViewById(R.id.account_info_layout);
		unsubcribe = findViewById(R.id.account_unsubscribe);
		changepass = findViewById(R.id.account_change_pass);
		logout = findViewById(R.id.account_logout);
		showAccountInfo.setOnClickListener(this);
		unsubcribe.setOnClickListener(this);
		changepass.setOnClickListener(this);
		logout.setOnClickListener(this);

		// update Views' status
		updateUI();
	}

	ShowHideBottomPlayerListener showHideBottomPlayerListener = new ShowHideBottomPlayerListener() {

		@Override
		public void onShowBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.VISIBLE);
		}

		@Override
		public void onHideBottomPlayer() {
			// TODO Auto-generated method stub
			mViewReplacePlayer.setVisibility(View.GONE);
		}
	};

	@Override
	protected void onPause() {
		super.onPause();
		mBottomPlayerView.stopUpdate();
	}

	public void showPhotoChooser(final JsonSong song) {
		// song.songs = new ArrayList<Song>();
		//
		// Song newSong = new Song();
		// newSong.id = 1;
		// newSong.album_title = "Bình Thường";
		//
		// song.songs.add(newSong);
		//
		// newSong = new Song();
		// newSong.id = 2;
		// newSong.album_title = "Chất lượng cao";
		//
		// song.songs.add(newSong);
		//
		// final Dialog dialog = new Dialog(mContext);
		// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// dialog.setContentView(R.layout.layout_dialog_context_menu);
		// dialog.setCancelable(true);
		// ListView _listview = (ListView) dialog
		// .findViewById(R.id.common_context_menu_listview);
		// Button _closeBtn = (Button) dialog
		// .findViewById(R.id.common_context_menu_close_btn);
		// _closeBtn.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// }
		// });
		//
		// MusicQualityListAdapter _myAdapter = new MusicQualityListAdapter(
		// mContext, song.songs);
		//
		// _listview.setAdapter(_myAdapter);
		//
		// TextView _title = (TextView) dialog
		// .findViewById(R.id.common_context_menu_title_txt);
		// _title.setText("Chọn chất lượng nhạc");
		//
		// dialog.show();
		//
		// _listview.setOnItemClickListener(new OnItemClickListener() {
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// // do something
		//
		// dialog.dismiss();
		// Song songConfig = (Song) parent.getItemAtPosition(position);
		// dataStore.setConfig(Const.MUSIC_QUALITY_ID, songConfig.id + "");
		// dataStore.setConfig(Const.MUSIC_QUALITY_VALUE,
		// songConfig.album_title + "");
		// musicQualityTextView.setText(songConfig.album_title);
		//
		// }
		// });
	}

	private void showDialog(final JsonSong json) {
		// ArrayList<String> list = new ArrayList<String>();
		// for (Song song : json.songs) {
		// list.add(song.title);
		// }
		// CharSequence[] items = list.toArray(new CharSequence[list.size()]);
		// Builder builder = new Builder(mContext);
		// builder.setTitle(R.string.music_quality);
		// builder.setItems(items, new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog, int item) {
		// Song songConfig = json.songs.get(item);
		// dataStore.setConfig(Const.MUSIC_QUALITY_ID, songConfig.id + "");
		// dataStore.setConfig(Const.MUSIC_QUALITY_VALUE, songConfig.title
		// + "");
		// musicQualityTextView.setText(songConfig.title);
		// }
		// });
		//
		// builder.setNegativeButton(R.string.cancel, null);
		// builder.show();

	}

	OnClickListener onUploadAvatarBtnListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			// Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
			// startActivityForResult(intent, 0);
			showPhotoChooser();
		}
	};

	public void uploadAvatarToServer(final Bitmap avatar) {

		// mProgressDialog = new ProgressDialog(mContext);
		// mProgressDialog.setMessage("Hình ảnh đang được tải lên...");
		// mProgressDialog.setCancelable(false);
		// mProgressDialog.show();
		// new Thread(new Runnable() {
		// @Override
		// public void run() {
		// try {
		// Bitmap bm = getResizedBitmap(avatar, 80, 80);
		//
		// FileStorage _fileStorage = new FileStorage();
		// FileOutputStream out = new FileOutputStream(
		// _fileStorage.getAvatarCachePath());
		// bm.compress(Bitmap.CompressFormat.PNG, 80, out);
		//
		// JsonAuth json = JsonAuth.uploadAvatar(bm);
		//
		// if (json.isSuccess())
		// mHandler.sendEmptyMessage(UPLOAD_AVATAR_SUCCESS);
		// else
		// mHandler.sendEmptyMessage(UPLOAD_AVATAR_FAILED);
		//
		// } catch (Exception e) {
		// // TODO: handle exception
		// mHandler.sendEmptyMessage(UPLOAD_AVATAR_FAILED);
		// }
		// }
		// }).start();

	}

	public void handleActivityResult(int requestCode, int resultCode,
			Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == VALUE_CAMERA) {
			if (data != null) {
				try {
					Bitmap photo = (Bitmap) data.getExtras().get("data");
					photo = Bitmap.createScaledBitmap(photo, 80, 80, false);
					// imgAvatar.setBackgroundResource(0);
					imgAvatar.setImageBitmap(photo);
					// Bitmap bm = getResizedBitmap(photo, 80, 80);
					uploadAvatarToServer(photo);
					photo = null;
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			} else {

			}
		} else if (requestCode == VALUE_GALLERY) {
			if (data != null) {
				Uri chosenImageUri = data.getData();
				// try {
				Bitmap mBitmap = readBitmap(chosenImageUri);
				// ImageView avatar =
				// (ImageView)findViewById(R.id.account_info_avatar);
				imgAvatar.setImageBitmap(mBitmap);
				// imgAvatar.refreshDrawableState();
				// Bitmap bm = getResizedBitmap(mBitmap, 80, 80);
				uploadAvatarToServer(mBitmap);
				mBitmap = null;
				// } catch (FileNotFoundException e) {
				// // TODO Auto-generated catch block
				// // e.printStackTrace();
				// } catch (IOException e) {
				// // TODO Auto-generated catch block
				// // e.printStackTrace();
				// }

			} else {

			}
		}
	}

	public Bitmap readBitmap(Uri contentUri) {
		String imagePath = getRealPathFromURI(contentUri);
		File image = new File(imagePath);
		if (!image.exists()) {
			return null;
		}
		Bitmap bm = null;
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 5;
		FileDescriptor fileDescriptor = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(image);
			fileDescriptor = in.getFD();
			bm = BitmapFactory.decodeFileDescriptor(fileDescriptor, null,
					options);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bm;
	}

	public String getRealPathFromURI(Uri contentUri) {

		// can post image
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(contentUri, proj, // Which columns to
														// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();

		return cursor.getString(column_index);
	}

	public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {

		int width = bm.getWidth();

		int height = bm.getHeight();

		float scaleWidth = ((float) newWidth) / width;

		float scaleHeight = ((float) newHeight) / height;

		// create a matrix for the manipulation

		Matrix matrix = new Matrix();

		// resize the bit map

		matrix.postScale(scaleWidth, scaleHeight);

		// recreate the new Bitmap

		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
				matrix, false);

		return resizedBitmap;

	}

	public void showPhotoChooser() {
		// final Dialog dialog = new Dialog(mContext);
		// dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		// dialog.setContentView(R.layout.layout_dialog_context_menu);
		// dialog.setCancelable(true);
		// ListView _listview = (ListView) dialog
		// .findViewById(R.id.common_context_menu_listview);
		// Button _closeBtn = (Button) dialog
		// .findViewById(R.id.common_context_menu_close_btn);
		// _closeBtn.setOnClickListener(new OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// dialog.dismiss();
		// }
		// });
		// DialogAdapter _myAdapter = new DialogAdapter(mContext);
		// _listview.setAdapter(_myAdapter);
		//
		// TextView _title = (TextView) dialog
		// .findViewById(R.id.common_context_menu_title_txt);
		// _title.setText("Chọn ảnh");
		// dialog.show();
		// _listview.setOnItemClickListener(new OnItemClickListener() {
		// public void onItemClick(AdapterView<?> parent, View view,
		// int position, long id) {
		// // do something
		// if (position == 0) {
		// dialog.dismiss();
		// Intent intent = new Intent(
		// "android.media.action.IMAGE_CAPTURE");
		// getParent().startActivityForResult(intent, VALUE_CAMERA);
		// } else if (position == 1) {
		// dialog.dismiss();
		// Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		// photoPickerIntent.setType("image/*");
		// getParent().startActivityForResult(photoPickerIntent,
		// VALUE_GALLERY);
		// }
		// }
		// });
	}

	private class DialogAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		class ViewHolder {
			TextView first_text;
			ImageView image;
			ImageView arrow;

		}

		public DialogAdapter(Context context) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return 2;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.view_listview_row_context_menu, null);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.common_context_menu_row_thumbnail_img);
				holder.arrow = (ImageView) convertView
						.findViewById(R.id.common_context_menu_row_arrow_img);
				holder.first_text = (TextView) convertView
						.findViewById(R.id.common_context_menu_row_first_txt);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.image.setVisibility(ImageView.VISIBLE);
			holder.arrow.setVisibility(ImageView.VISIBLE);
			holder.arrow.setBackgroundResource(R.drawable.ic_listview_arrow);

			RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
					RelativeLayout.LayoutParams.WRAP_CONTENT,
					RelativeLayout.LayoutParams.WRAP_CONTENT);
			lp2.rightMargin = 20;
			lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
			lp2.addRule(RelativeLayout.CENTER_VERTICAL);
			holder.arrow.setLayoutParams(lp2);

			if (position == 0) {
				holder.image.setBackgroundResource(R.drawable.ic_app);
				holder.first_text.setText("Chụp từ camera");
			} else if (position == 1) {
				holder.image.setBackgroundResource(R.drawable.ic_app);
				holder.first_text.setText("Lấy ảnh có sẵn");
			}

			return convertView;
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		// update Views' status
		mBottomPlayerView.startUpdate();
		int used = (int) (FileStorage.getUsedSize() / FileStorage.MBYTE);

		if (memoryCurrentuse != null) {
			memoryCurrentuse.setText(getStringOfSize(used));
		}
		if (dataStore.getConfig(Const.KEY_FULL_NAME).equals("")) {
			txtFullName.setText(dataStore.getMsisdn());
		} else {
			txtFullName.setText(dataStore.getConfig(Const.KEY_FULL_NAME));
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		// switch (id) {
		// case DIALOG_LOGOUT:
		// return new AlertDialog.Builder(mContext)
		// .setIcon(android.R.drawable.ic_dialog_alert)
		// .setTitle(R.string.app_name)
		// .setMessage(R.string.logout_msg)
		// .setPositiveButton(R.string.confirm_yes,
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int whichButton) {
		// getParent().finish();
		// }
		// })
		// .setNegativeButton(R.string.confirm_no,
		// new DialogInterface.OnClickListener() {
		// public void onClick(DialogInterface dialog,
		// int whichButton) {
		// // do nothing
		// }
		// }).create();
		// }
		return null;
	}

	private String getStringOfSize(int sizeInMB) {
		if (sizeInMB < 1024)
			return sizeInMB + " MB";

		int sizeInGB = sizeInMB / 1024;
		return sizeInGB + " GB";
	}

	private void updateUI() {
		DataStore dataStore = DataStore.getInstance();

		// Get Memory Info
		int used = (int) (FileStorage.getUsedSize() / FileStorage.MBYTE);
		int free = (int) (FileStorage.getAvaiableVolume() / FileStorage.MBYTE);
		int maxUsed = used + free;

		// Total Memory (maximum memory amount allowed)
		totalMemorySeekBar.setMax(100);
		int progress = dataStore.getMemoryLimit();
		totalMemorySeekBar.setProgress(progress);
		memoryPercentUse.setText(getString(R.string.allowed_memory) + " ("
				+ progress + " %)");
		memoryMax.setText(getStringOfSize(maxUsed));
		int limit = maxUsed * progress / 100;
		memoryAllow.setText(getStringOfSize(limit));
		memoryCurrentuse.setText(getStringOfSize(used));

		// Account Information
		txtFullName.setText(dataStore.getConfig(KEY_FULL_NAME));
		txtPhoneNumber.setText(dataStore.getConfig(KEY_PHONE_NUMBER));
		FileStorage fileStorage = new FileStorage();
		String avatarPath = fileStorage.getAvatarCachePath();
		if (Util.checkStringIsemptyOrNull(avatarPath)) {
			Bitmap myBitmap = BitmapFactory.decodeFile(fileStorage
					.getAvatarCachePath());
			if (myBitmap != null) {
				imgAvatar.setImageBitmap(myBitmap);
			} else {
				mApp.mImageLoader.download(dataStore.getConfig(KEY_AVATAR),
						imgAvatar);
			}
		} else {
			mApp.mImageLoader.download(dataStore.getConfig(KEY_AVATAR),
					imgAvatar);
		}
	}

	private void restartApp(String message) {
		// AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
		// alertDialog.setTitle(getText(R.string.dialog_notification));
		// alertDialog.setMessage(message);
		// alertDialog.setButton("Đóng", new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.dismiss();
		// JsonBase.clearServerSessionInvalidListener();
		// // Stop download thread
		// DownloadManager.stopDownload();
		// // Stop sync thread
		// SynchronizeManager.stopSyncThread();
		// // Stop MusicPlayer
		// MusicPlayer.stopMusicPlayer();
		// // logout
		// JsonAuth.logout();
		//
		// Bundle bundle = new Bundle();
		// bundle.putBoolean(LoginActivity.NEED_AUTHENTICATION, true);
		// bundle.putString(Const.KEY_MSISDN, dataStore.getMsisdn());
		// bundle.putString(Const.KEY_PASSWORD,
		// dataStore.getSavedPassword());
		//
		// // clear old login info
		// dataStore.setMsisdn("");
		// dataStore.setPassword("");
		//
		// bundle.putBoolean(Const.BUNDLE_IS_LOGOUT, true);
		// Intent intent = new Intent(mContext, LoginActivity.class);
		// intent.putExtras(bundle);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
		// | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		// startActivity(intent);
		// finish();
		// }
		// });
		// alertDialog.show();
	}

	public void showAccountInfo() {
		if (dataStore == null) {
			dataStore = DataStore.getInstance();
		}
		String isOff = dataStore.getConfig(Const.OFFLINE_MODE);
		if (isOff != null && isOff.equalsIgnoreCase(Const.VALUE_OFFLINE)) {
			showProgress("Đang lấy thông tin tài khoản...");
			new Thread(new Runnable() {
				@Override
				public void run() {
					identify = JsonAuth.identify();
					if (!identify.isSuccess()) {
						mHandler.sendEmptyMessage(GET_ACC_INFO_FAILED);
					} else {
						mHandler.sendEmptyMessage(GET_ACC_INFO_SUCCESS);
					}
				}
			}).start();
		} else {
			String packageCode = dataStore.getConfig(Const.KEY_PACKAGE_CODE);
			if (Util.checkStringIsemptyOrNull(packageCode)) {
				if (!Util.checkStringIsemptyOrNull(Appinstant.warningMessage)) {
					Util.showAlert(SettingAccount.this, Appinstant.warningMessage);
				} else {
					Util.showAlert(SettingAccount.this, getString(R.string.your_phone_number_not_register_any_package));
				}
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.append("Bạn đang sử dụng gói cước "
					+ dataStore.getConfig(Const.KEY_PACKAGE_CODE));
			stringBuilder.append(".\n");
			stringBuilder.append("Thời hạn sử dụng dến "
					+ dataStore.getConfig(Const.KEY_END_DATE));
			Util.showAlert(SettingAccount.this, stringBuilder.toString());
		}
	}

	private void logout() {
		// show Confirm dialog
		if (logoutDialog != null) {
			logoutDialog.show();
			return;
		}

		logoutDialog = new ChaChaDialog(this, null);
		logoutDialog.setCancelable(true);
		logoutDialog.hideCloseDefaultBtn();
		logoutDialog.setTitle("Đăng thoát!");
		logoutDialog.setMessage(getString(R.string.setting_confirm_logout));
		View.OnClickListener yesClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logoutDialog.dismiss();
				showProgress("Đang thoát...");
				new Thread(new Runnable() {
					@Override
					public void run() {
						JsonAuth jsonAuth = JsonAuth.logout();
						if (jsonAuth.isSuccess()) {
							mHandler.sendEmptyMessage(LOGOUT_SUCCESS);
						} else {
							mHandler.sendEmptyMessage(LOGOUT_FAIL);
						}
					}
				}).start();
			}
		};

		View.OnClickListener noClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				logoutDialog.dismiss();
			}
		};
		logoutDialog.addButton(getString(R.string.confirm_yes),
				yesClickListener);
		logoutDialog.addButton(getString(R.string.confirm_no), noClickListener);
		logoutDialog.show();
	}

	

	private void unsubcribe() {
		String packageCode = dataStore.getConfig(Const.KEY_PACKAGE_CODE);
		if (Util.checkStringIsemptyOrNull(packageCode)) {
			showToast("Bại chưa đăng kí dịch vụ!");
			return;
		}
		
		if (unsubscriDialog == null) {
			unsubscriDialog = new ChaChaDialog(this, null);
			unsubscriDialog.setCancelable(true);
			unsubscriDialog.hideCloseDefaultBtn();
			unsubscriDialog.setTitle("Hủy dịch vụ!");
			unsubscriDialog
					.setMessage(getString(R.string.setting_confirm_unsubscribe));
			View.OnClickListener yesClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					unsubscriDialog.dismiss();
					showProgress("Đang hủy dịch vụ...");
					new Thread(new Runnable() {
						@Override
						public void run() {
							unsubscribe = JsonAuth.unsubscribe();
							if (unsubscribe.isSuccess()) {
								mHandler.sendEmptyMessage(UNSUBCRIBE_SUCCESS);
							} else {
								mHandler.sendEmptyMessage(UNSUBCRIBE_FAILED);
							}
						}
					}).start();
				}
			};

			View.OnClickListener noClickListener = new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					unsubscriDialog.dismiss();
				}
			};
			unsubscriDialog.addButton(getString(R.string.confirm_yes),
					yesClickListener);
			unsubscriDialog.addButton(getString(R.string.confirm_no),
					noClickListener);
		}
		unsubscriDialog.show();
	}

	private ChaChaDialog changePassDialog;
	private TextBox oldPass;
	private TextBox newPass;
	private TextBox newPassReenter;
	OnCloseDialogListener closeDialogListener = new OnCloseDialogListener() {

		@Override
		public void onClose() {
			// TODO Auto-generated method stub
			if (oldPass != null) {
				oldPass.setText("");
			}
			if (newPass != null) {
				newPass.setText("");
			}
			if (newPassReenter != null) {
				newPassReenter.setText("");
			}
		}
	};

	private void changePassWord() {
		if (changePassDialog != null) {
			changePassDialog.show();
			return;
		}
		changePassDialog = new ChaChaDialog(this, closeDialogListener);
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View dialogContent = inflater.inflate(R.layout.view_change_pass, null);
		oldPass = (TextBox) dialogContent.findViewById(R.id.textBox_old_pass);
		newPass = (TextBox) dialogContent.findViewById(R.id.textBox_new_pass);
		newPassReenter = (TextBox) dialogContent
				.findViewById(R.id.textBox_reenter_new_pass);
		oldPass.setTextColor("#116E9D");
		newPass.setTextColor("#116E9D");
		newPassReenter.setTextColor("#116E9D");
		oldPass.setIsPassword(true);
		newPass.setIsPassword(true);
		newPassReenter.setIsPassword(true);
		oldPass.setTextHintColor("#666666");
		newPass.setTextHintColor("#666666");
		newPassReenter.setTextHintColor("#666666");
		oldPass.setTextHint("Mật khẩu hiện tại");
		newPass.setTextHint("Mật khẩu mới");
		newPassReenter.setTextHint("Nhập lại mật khẩu mới");
		oldPass.setBackground(R.drawable.bg_login_edittext);
		newPass.setBackground(R.drawable.bg_login_edittext);
		newPassReenter.setBackground(R.drawable.bg_login_edittext);

		View.OnClickListener noClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				changePassDialog.dismiss();
			}
		};

		View.OnClickListener yesClickListener = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				final String old = oldPass.getText();
				final String newPassWord = newPass.getText();
				String newPassWordReeneter = newPassReenter.getText();
				if (invalidChangepass(old, newPassWord, newPassWordReeneter)) {
					changePassDialog.dismiss();
					showProgress("Đang đổi mật khẩu...");

					new Thread() {
						@Override
						public void run() {
							String username = dataStore
									.getConfig(KEY_PHONE_NUMBER);
							String passOld = Util.encodeHttpParamas(old);
							String passNew = Util
									.encodeHttpParamas(newPassWord);
							username = Util.encodeHttpParamas(username);
							JsonAuth jsonAuth = JsonAuth.changePassword(
									username, passOld, passNew);
							if (jsonAuth.isSuccess()) {
								mHandler.sendEmptyMessage(CHANGE_PASS_SUCCESS);
							} else {
								mHandler.sendEmptyMessage(CHANGE_PASS_FAIL);
							}
						}
					}.start();
				}
			}
		};

		changePassDialog.hideCloseDefaultBtn();
		changePassDialog.setTitle("Đổi mật khẩu");
		changePassDialog.setCancelable(true);
		changePassDialog.setContentView(dialogContent);
		changePassDialog.addButton("Thực hiện", yesClickListener);
		changePassDialog.addButton("Hủy", noClickListener);

		changePassDialog.show();
	}

	private boolean invalidChangepass(String oldPass, String newPass,
			String newPassreenter) {
		if (Util.checkStringIsemptyOrNull(oldPass)
				|| Util.checkStringIsemptyOrNull(newPass)
				|| Util.checkStringIsemptyOrNull(newPassreenter)) {
			showToast("Bạn cần nhập đủ thông tin!");
			return false;
		}
		if (!newPass.equals(newPassreenter)) {
			showToast("Mật khẩu mới không khớp!");
			return false;
		}

		return true;
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// if (progress < totalMemorySeekBarMinProgress) {
		// totalMemorySeekBar.setProgress(totalMemorySeekBarMinProgress);
		// } else {
		// // update UI
		// totalMemoryPercentTextView.setText(progress + " %");
		if (fromUser) {
			updateMemoryView(progress);
		}
		// }
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {

	}

	private void updateMemoryView(int progress) {
		// update UI
		int used = (int) (FileStorage.getUsedSize() / FileStorage.MBYTE);
		int free = (int) (FileStorage.getAvaiableVolume() / FileStorage.MBYTE);
		int maxUsed = used + free;
		memoryPercentUse.setText(getString(R.string.allowed_memory) + " ("
				+ progress + " %)");
		memoryMax.setText(getStringOfSize(maxUsed));
		int limit = maxUsed * progress / 100;
		memoryAllow.setText(getStringOfSize(limit));
		memoryCurrentuse.setText(getStringOfSize(used));
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		int progress = seekBar.getProgress();
		updateMemoryView(progress);
		// store preference
		dataStore.setMemoryLimit(progress);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.account_logout:
			logout();
			break;
		case R.id.account_change_pass:
			changePassWord();
			break;
		case R.id.account_unsubscribe:
			unsubcribe();
			break;
		case R.id.account_info_layout:
			showAccountInfo();
			break;
		case R.id.account_info_avatar:

			break;

		default:
			break;
		}

	}
}
